package yt.demo.appcommontools.utils;

import lombok.extern.slf4j.Slf4j;
import yt.demo.appcommonbean.exception.LogicException;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ObjectToMapUtils {

    // 将对象转为Map的方法
    public static Map<String, Object> convertObjectToMap(Object obj) {
        // 创建一个空的Map
        Map<String, Object> map = new HashMap<>();
        // 获取对象的所有字段
        Field[] fields = obj.getClass().getDeclaredFields();
        // 遍历字段，将字段名和字段值添加到Map中
        for (Field field : fields) {
            field.setAccessible(true); // 设置字段可访问
            try {
                map.put(field.getName(), field.get(obj));
            } catch (IllegalAccessException e) {
                throw new LogicException(e.getMessage());
            }
        }
        return map;
    }

    public static <T> T convertToObject(String key,Object result, Class<T> clazz) {
        Map<String, Object> restResponse = ObjectToMapUtils.convertObjectToMap(result);
        Object value = restResponse.get(key);
        return clazz.cast(value);
    }

    public static <T> T convertToClazz(Object result, Class<T> clazz) {

        return clazz.cast(result);
    }
}
